var g_viewId = "";
var g_currentToken = "";
var g_currentUserName = "";
var g_opinionId = "";
var g_commentsOrder;
var g_subCommentsOrder;

var g_firstComment = 0;
var k_opinionsPerPage = 5;

var g_subCommentsOrderMap = {};
var g_pathToVote = new Array();

var g_deleteOp;
var g_deleteDialog;

function processOpinionsResponse(data, sEcho) {
	response = {};
	response["sEcho"] = sEcho;
	response["iTotalRecords"] = data["totalResults"];
	response["iTotalDisplayRecords"] = data["totalResults"];
	pageObj = data["page"];
	for (indx in pageObj) {
		titleHtml = "<a href='javascript:gotoViewArticle(\"" + pageObj[indx].id + "\")'>" + pageObj[indx].title + "</a>";
		pageObj[indx].title = titleHtml;
		pageObj[indx].general = pageObj[indx].positive - pageObj[indx].negative;
		if (pageObj[indx].creator) {
			pageObj[indx].creator = pageObj[indx].creator.id;
		} else {
			pageObj[indx].creator = "noone";
		}

	}

	response["aaData"] = pageObj;
	return response;
}

function onOpinionFailure(data, textStatus) {
	responseText = data.responseText;
	jsonObj = $.parseJSON(responseText);
	alert("" + jsonObj.errorCode + ": " + jsonObj.error_msg);
}

function opinionsServerData(sSource, aoData, fnCallback, oSettings) {

	aoData.push({
		"name" : "view_id",
		"value" : g_viewId
	});
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	switch (oSettings.aaSorting[0][0]) {
	case 3:
		aoData.push({
			"name" : "order",
			"value" : "most_positive"
		});
		break;
	case 4:
		aoData.push({
			"name" : "order",
			"value" : "most_negative"
		});
		break;
	case 5:
		aoData.push({
			"name" : "order",
			"value" : "general_attention_desc"
		});
		break;
	case 6:
		aoData.push({
			"name" : "order",
			"value" : "most_attended"
		});
		break;

	case 7:
		if (oSettings.aaSorting[0][1] === "desc") {
			aoData.push({
				"name" : "order",
				"value" : "newest"
			});
		} else if (oSettings.aaSorting[0][1] === "asc") {
			aoData.push({
				"name" : "order",
				"value" : "oldest"
			});
		}
		break;
	}

	aoData.push({
		"name" : "offset",
		"value" : oSettings._iDisplayStart
	});
	aoData.push({
		"name" : "limit",
		"value" : oSettings._iDisplayLength
	});
	aoData.push({
		"name" : "max_content_length",
		"value" : 100
	});

	oSettings.jqXHR = $.ajax({
		"dataType" : 'json',
		"type" : "GET",
		"url" : sSource,
		"data" : aoData,
		"success" : function(data, textStatus, jqXHR) {
			newData = processOpinionsResponse(data, oSettings.iDraw);
			fnCallback(newData, textStatus, jqXHR);
		},
		"error" : onOpinionFailure
	});
}

function gotoListArticles(country) {
	g_opinionId = "";
	
	if (country) {
		g_viewId = country;
	} else {
		g_viewId = 'all_base_opinions';
	}

	$('#td_content').load("list_articles.html", function() {
		$('#articles_table').dataTable({
			"bProcessing" : true,
			"bServerSide" : true,
			"sAjaxSource" : "/view/list_opinions",
			"fnServerData" : opinionsServerData,
			"sDom" : "lrtip",
			//default sorting
			//"aaSorting" : [ [ 3, "desc" ] ],
			"aaSorting" : [ [ 6, "desc" ] ],
			"aoColumns" : [ {
				"mData" : "title",
				"bSortable" : 0
			}, {
				"mData" : "text",
				"bSortable" : 0
			}, {
				"mData" : "creator",
				"bSortable" : 0
			}, {
				"mData" : "positive",
				"asSorting" : [ "desc" ]
			}, {
				"mData" : "negative",
				"asSorting" : [ "desc" ]
			}, {
				"mData" : "general",
				"asSorting" : [ "desc" ]
			}, {
				"mData" : "total",
				"asSorting" : [ "desc" ]
			}, {
				"mData" : "created"
			} ]
		});
	});

}

function gotoCreateArticle() {
	$('#td_content').load("create_article.html");
	g_opinionId = "";
}

function gotoViewArticle(articleId) {
	$('#td_content').load("view_article.html", function() {
		
		g_deleteDialog = $( "#dialog-deletion" ).dialog({
			modal: true,
			autoOpen: false,
			position: 'center',
			buttons: {
				"Delete comment": function() {
					$( this ).dialog( "close" );
					deleteOpinion(g_deleteOp.id);
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			}
		});
		
		topPositiveFunc = function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'evaluation_order' : 'positive',
				'order' : 'most_positive',
				'max_depth': 1,
				'max_subopinions': k_opinionsPerPage
			},
			{
				'tree_order' : 'breadth_first',
				'order' : 'most_positive',
				'max_subopinions': 3,
				'max_depth': 2
			});
		};
		$('#order_type > #top_positive').click(topPositiveFunc);
		
		$('#order_type > #top_negative').click(function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'evaluation_order' : 'negative',
				'order' : 'most_positive',
				'max_depth': 1,
				'max_subopinions': k_opinionsPerPage
			},
			{
				'tree_order' : 'breadth_first',
				'order' : 'most_positive',
				'max_subopinions': 3,
				'max_depth': 2
			});
		});
		
		$('#order_type > #latest').click(function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'order' : 'newest',
				'max_depth': 3,
				'max_subopinions': k_opinionsPerPage
			}, null);
		});
		
		$('#order_type > #oldest').click(function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'order' : 'oldest',
				'max_depth': 3,
				'max_subopinions': k_opinionsPerPage
			}, null);
		});
		
		$('#order_type > #most_supported').click(function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'order' : 'most_positive',
				'max_depth': 1,
				'max_subopinions': k_opinionsPerPage
			}, null);
		});
		
		$('#order_type > #most_disliked').click(function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'order' : 'most_negative',
				'max_depth': 1,
				'max_subopinions': k_opinionsPerPage
			}, null);
		});
		
		$('#order_type > #most_popular').click(function() {
			setCommentsOrder({
				'tree_order' : 'depth_first',
				'order' : 'general_attention_desc',
				'max_depth': 1,
				'max_subopinions': k_opinionsPerPage
			}, null);
		});
		
		if (articleId) {
			g_opinionId = articleId;
		}
		g_firstComment = 0;
		topPositiveFunc();
	});
	
}

function setUserAccessToken(user, accessToken) {
	login_div = $('#login_div_' + user);
	g_currentUserName = user;
	if (login_div.length) {
		inputFld = login_div.children("input")[0];
		inputFld.value = accessToken;
		g_currentToken = inputFld.value;
		inputFld.checked = true;
	} else {
		$('#login_choice').append(
				'<div id="login_div_' + user + '"><input type="radio" name="login" value="' + accessToken + '">' + user + '</div><br/>');
		inputFld = $('#login_div_' + user + ' > input');
		inputFld.attr('checked', true);
		g_currentToken = inputFld.val();
		inputFld.click(function() {
			g_currentToken = $(this).val();
			g_currentUserName = user;
			if (g_opinionId) {
				g_firstComment = 0;
				sendArticleRequest(false);
			}
		});
	}
	
	if (g_opinionId) {
		g_firstComment = 0;
		sendArticleRequest(false);
	}
}

function doLogin(onLogin) {
	uName = $('#u_name').val();
	uPass = $('#u_pass').val();
	isModerator = $('#is_moderator').is(':checked');
	aoData = [];
	aoData.push({
		"name" : "user_id",
		"value" : uName
	});
	aoData.push({
		"name" : "password",
		"value" : uPass
	});
	if (isModerator) {
		aoData.push({
			"name" : "scope",
			"value" : "all:rc bopin_c bopin_r Bulgaria:m France:m Australia:m"
		});
	} else {
		aoData.push({
			"name" : "scope",
			"value" : "all:rc all:l"
		});
	}

	// alert(uName);
	$.ajax({
		"dataType" : 'json',
		"type" : "POST",
		"url" : "/auth/authorize",
		"data" : aoData,
		"success" : function(data, textStatus, jqXHR) {
			setUserAccessToken(uName, data['access_token']);
			if (onLogin){
				onLogin();
			}
		},
		"error" : onOpinionFailure
	});
}

function doSubmitArticle() {
	title = $('#title_id').val();
	content = $('#content_id').val();

	aoData = [];
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	aoData.push({
		"name" : "title",
		"value" : title
	});
	aoData.push({
		"name" : "content",
		"value" : content
	});

	// All groups can create a read, article_moderators can delete. For all
	// articles
	aoData.push({
		"name" : "group_permissions",
		"value" : "article_moderators:d sent_default_group:rc"
	});

	$.ajax({
		"dataType" : 'json',
		"type" : "POST",
		"url" : "/opinion/create_base_opinion",
		"data" : aoData,
		"success" : function(data) {
			viewId = title = $('#country_select').val();

			aoData1 = [];
			aoData1.push({
				"name" : "access_token",
				"value" : g_currentToken
			});
			aoData1.push({
				"name" : "opinion_ids",
				"value" : data['id']
			});
			aoData1.push({
				"name" : "view_id",
				"value" : viewId
			});

			$.ajax({
				"dataType" : 'json',
				"type" : "POST",
				"url" : "/view/add_opinions",
				"data" : aoData1,
				"success" : function(data1) {
					alert("done");
				}
			});

		},
		"error" : onOpinionFailure
	});
}

function setCommentsOrder(order, sub_order) {
	g_commentsOrder = order;
	order['subopinions_desc'] = sub_order;
	g_subCommentsOrder = sub_order;
	g_firstComment = 0;
	sendArticleRequest(false);
}

function showMoreComments() {
	g_firstComment += k_opinionsPerPage;
	sendArticleRequest(true);
}

function setCommentEval(td, evalValue) {
	td.text(evalValue);
	switch (evalValue){
	case "+":
		td.css('background-color', '#7BD580');
		break;
	case "-":
		td.css('background-color', '#F78A8A');
		break;
	case "=":
		td.css('background-color', '#FFFF91');
		break;
	}
}

/**
 * Returns what impact has the current user for a given opinion
 * @param opId The opinion we are interested in
 * @returns {Number} Positive if the opinion increases the positive attention, 
 * negative if the opinion increases the negative attention, 0 if no impact.
 * abs(result)=1 if my opinion is in normal state, abs(result)=2 if my opinion is inserted
 */
function getThisUserImpact(opId) {
	
	if (g_pathToVote.length > 0) {
		var result;
		myOp = g_pathToVote[g_pathToVote.length - 1];
		if (myOp.creator.id != g_currentUserName) {
			alert("myOp.creator.id != g_currentUserName: " + myOp.creator.id + " " + g_currentUserName);
			return 0;
		}
		
		myOpEval = myOp.eval;
		
		if (myOp.state == 'wu') {
			myOpEval = myOp.prev_eval;
		}
		
		if (myOpEval == "+"){
			if (myOp.state == 'i') {
				result = 2;
			} else {
				result = 1;
			}
			
		} else if (myOpEval == "-"){
			if (myOp.state == 'i') {
				result = -2;
			} else {
				result = -1;
			}
		} else {
			alert("wrong eval " + myOpEval);
			return 0;
		}
		
		//skip my op
		for (var indx = g_pathToVote.length - 2; indx >= 0; indx--) {
			if (g_pathToVote[indx].id == opId) {
				return result;
			}
			if (g_pathToVote[indx].eval == "+") {
				//nop
			} else if (g_pathToVote[indx].eval == "-") {
				result = -result;
			} else {
				//this opinion is neutral => cuts the chain
				return 0;
			}
		}
		return 0;
	} else {
		return 0;
	}
	
}

function setMeInValue(val) {
	if (val > 0) {
		return "<b>" + val + " + you</b>";
	} else {
		return "<b>1 (you)</b>";
	}
}

function setTextNegativePositive(npObject, commentData) {
	var impact = getThisUserImpact(commentData.id);
	if (impact != 0) {
		if (impact > 0) {
			if (impact == 1) {
				npObject.positiveText -= 1;
			}
			npObject.positiveText = setMeInValue(npObject.positiveText);
		} else if (impact < 0){
			if (impact == -1) {
				npObject.negativeText -= 1;
			}
			npObject.negativeText = setMeInValue(npObject.negativeText);
		}
	}
}

function expandTextAreaOnKeyUp() {
	this.style.height = "";
	this.style.height = Math.min(this.scrollHeight + 2, 300) + "px";
}

function displayComment(commentData, receiverElement, positionFunction, skip_data_refresh){
	var newDiv = $('#comment-' + commentData.id);
	
	if (newDiv.length == 0) {
		var newDivStr = "<div id='comment-" + commentData.id + "'>" + $('#comment_template').html() + "</div>";
		
		if (positionFunction){
			positionFunction(newDivStr);
		} else {
			var receiver = $(receiverElement);
			receiver.append(newDivStr);
		}
		newDiv = $('#comment-' + commentData.id);
		
		$('#sub_comments', newDiv).attr('id', 'sub_comments-' + commentData.id);
		
		$('#show_more_comments_a:last', newDiv).click(function(){
			sendCommentsRequest(commentData.id);
		});
		
		$("#comment_form textarea", newDiv).keyup(expandTextAreaOnKeyUp);
	}
	//newDiv.css('visibility', 'visible');
	//newDiv.attr("id", "comment" + commentData.id);
	if (!skip_data_refresh) {
		$('#comment:first', newDiv).text(commentData.title);
		
		if (commentData.creator){
			if (commentData.creator.id == g_currentUserName) {
				$('#commenter_name:first', newDiv).text(commentData.creator.id + "(you):");
				$('#comment_edit:first', newDiv).css("display", "table-cell");
				
				$('#comment_edit:first a:first', newDiv).off("click");
				$('#comment_edit:first a:first', newDiv).click({"op": commentData}, showEditDialog);
				
				$('#comment_edit:first a:last', newDiv).off("click");
				$('#comment_edit:first a:last', newDiv).click({"op": commentData}, showDeleteDialog);
			} else {
				$('#commenter_name:first', newDiv).text(commentData.creator.id + ":");
				$('#comment_edit:first', newDiv).css("display", "none");
			}
		} else {
			$('#comment_edit:first', newDiv).css("display", "none");
		}
	}
	
	setCommentEval($('#comment_eval:first', newDiv), commentData.eval);
	
	$('#total_attention:first', newDiv).text(commentData.total);
	
	$('#evaluations:first', newDiv).attr('id', "evaluations-" + commentData.id);
	
	npObject = {"positiveText": commentData.positive, 
				"negativeText": commentData.negative};
	
	setTextNegativePositive(npObject, commentData);
	
	positive_attention_span = $("#evaluations-" + commentData.id + ' #positive_attention', newDiv);
	positive_attention_span.html(npObject.positiveText);
	positive_attention_span.attr('int_value', commentData.positive);
	
	negative_attention_span = $("#evaluations-" + commentData.id + ' #negative_attention', newDiv);
	negative_attention_span.html(npObject.negativeText);
	negative_attention_span.attr('int_value', commentData.negative);
	
//	$('#num_positive_count:first', newDiv).text(commentData.num_positive_subops);
//	$('#num_negative_count:first', newDiv).text(commentData.num_negative_subops);
//	$('#num_neutral_count:first', newDiv).text(commentData.num_neutral_subops);
	
	//$('#show_more_comments_a', newDiv).attr('id', 'show_more_comments_a-' + commentData.id);
	
	//$('#show_more_comments_count:last', newDiv).attr('id', 'show_more_comments_count-' + commentData.id);
	commentFormSelector = '#sub_comments-' + commentData.id + " > #comment_form";
	
	var commentForm = $(commentFormSelector);
	
	displayFunction = function(commentDiv){
		commentForm.after(commentDiv);
	};
	
	$('#positive_opinion_button:first', newDiv).click(
			{'parent': commentData.id, 'evaluation': 'positive', 
				'commentFormSelector': commentFormSelector,
				'displayFunction': displayFunction}, 
			showCommentDialog);
	$('#negative_opinion_button:first', newDiv).click(
			{'parent': commentData.id,'evaluation': 'negative', 
				'commentFormSelector': commentFormSelector,
				'displayFunction': displayFunction}, 
			showCommentDialog);
	$('#neutral_opinion_button:first', newDiv).click(
			{'parent': commentData.id, 'evaluation': 'neutral', 
				'commentFormSelector': commentFormSelector,
				'displayFunction': displayFunction}, 
			showCommentDialog);
	
	var subComments = $('#sub_comments-' + commentData.id, newDiv);
	
	for (indx in commentData.sub_opinions) {
		displayComment(commentData.sub_opinions[indx], subComments[0]);
	}
	
	subCommentsDivs = $('#sub_comments-' + commentData.id + ' > div');
	numShownSubcomments = subCommentsDivs.length - 1; //one not displayed div for my comment
	
	vis = numShownSubcomments < commentData.total ? "inline" : "none";
	$('#show_more_comments_a:last', newDiv).css("display", vis);
	
	$('#show_more_comments_count:last', newDiv).text(commentData.total - numShownSubcomments);
}

function sendArticleRequest(commentsOnly) {
	step2 = function(){
		aoData = [];
		aoData.push({
			"name" : "access_token",
			"value" : g_currentToken
		});
		aoData.push({
			"name" : "opinion_id",
			"value" : g_opinionId
		});
		
		g_commentsOrder['first_subopinion'] = g_firstComment;
		
		aoData.push({
			"name" : "subopinions_desc",
			"value" : JSON.stringify(g_commentsOrder)
		});
		
		aoData.push({
			"name" : "max_content_length",
			"value" : 5000
		});
		
		if (commentsOnly){
			aoData.push({
				"name" : "subopinions_only",
				"value" : 1
			});
		}
		
		$.ajax({
			"dataType" : 'json',
			"type" : "POST",
			"url" : "/opinion/get",
			"data" : aoData,
			"success" : function(data) {
				if (!commentsOnly){
					g_subCommentsOrderMap = {};
					$('#article_title').text(data.title);
					$('#article_content').html(data.text);
					$('#article_comments').empty();
					$('#container > table:first').attr('id', "evaluations-" + data.id);
					
					npObject = {"positiveText": data.positive, 
								"negativeText": data.negative};
					
					positive_attention_span = $("#evaluations-" + data.id + " #positive_attention");
					negative_attention_span = $("#evaluations-" + data.id + " #negative_attention");
					
					setTextNegativePositive(npObject, data);
					
					positive_attention_span.html(npObject.positiveText);
					negative_attention_span.html(npObject.negativeText);
					
					positive_attention_span.attr('int_value', data.positive);
					negative_attention_span.attr('int_value', data.negative);
					
					$('#article_total_span').text(data.total);
				}
				
				var displayedComments = g_firstComment + k_opinionsPerPage;
				
				$('#num_comments_left').text(Math.max(data.total - displayedComments, 0));
				
				commentFormSelector = '#add_main_comment';
				displayFunction = function(commentDiv){
					$('#article_comments').append(commentDiv);
				};
				
				$("#add_main_comment input[name='support']").click(
						{'parent': data.id, 'evaluation': 'positive', 
							'commentFormSelector': commentFormSelector,
							'displayFunction': displayFunction}, postSubComment);
				$("#add_main_comment input[name='dislike']").click(
						{'parent': data.id,'evaluation': 'negative', 
							'commentFormSelector': commentFormSelector,
							'displayFunction': displayFunction}, postSubComment);
				$("#add_main_comment input[name='neutral']").click(
						{'parent': data.id,'evaluation': 'neutral', 
							'commentFormSelector': commentFormSelector,
							'displayFunction': displayFunction}, postSubComment);
				
				for (indx in data.sub_opinions) {
					displayComment(data.sub_opinions[indx], $('#article_comments')[0]);
				}
				
				displayPathToMyVote();
			}
		});
	};
	if (commentsOnly) {
		step2();
	} else {
		//$('#article_comments').empty();
		sendGetPathToMyVote(step2);
	}
}

function sendCommentsRequest(parentId){
	aoData = [];
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	aoData.push({
		"name" : "opinion_id",
		"value" : parentId
	});
	
	var subCommentsOrder;
	if(parentId in g_subCommentsOrderMap){
		subCommentsOrder = g_subCommentsOrderMap[parentId];
		subCommentsOrder.first_subopinion += subCommentsOrder.max_subopinions;
	} else {
		//subCommentsOrder = $.extend({}, g_subCommentsOrder);
		subCommentsOrder = {
			"first_subopinion": 0,
			'tree_order' : 'breadth_first',
			'order' : 'most_positive',
			'max_subopinions': 5,
			'max_depth': 1
		};
		g_subCommentsOrderMap[parentId] = subCommentsOrder;
	}
	
	aoData.push({
		"name" : "subopinions_desc",
		"value" : JSON.stringify(subCommentsOrder)
	});
	
	aoData.push({
		"name" : "max_content_length",
		"value" : 5000
	});
	
	aoData.push({
		"name" : "subopinions_only",
		"value" : 1
	});

	$.ajax({
		"dataType" : 'json',
		"type" : "POST",
		"url" : "/opinion/get",
		"data" : aoData,
		"success" : function(data) {
			//there is already div for the parent. displayComment will find it and reuse it
			displayComment(data, null, null, true);
		}
	});
}

function showCommentDialog(event){
	$('#sub_comments-' + event.data.parent + " > #comment_form").css('display', 'block');
	optionalText = $('#sub_comments-' + event.data.parent + " > #comment_form > #optional_comment");
	optionalText.css('visibility', 'visible');
	submit = $('#sub_comments-' + event.data.parent + " > #comment_form > input[type='submit']");
	if (event.data.evaluation == 'neutral') {
		optionalText.css('visibility', 'hidden');
		submit.attr('name', 'neutral');
	} else if (event.data.evaluation == 'positive') {
		submit.attr('name', 'support');
	} else if (event.data.evaluation == 'negative') {
		submit.attr('name', 'dislike');
	}
	submit.off("click");
	submit.click(event.data, postSubComment);
}

function showEditDialog(event){
	receiver = $('#comment-' + event.data.op.id + " #comment:first");
	$('#comment-' + event.data.op.id + " #comment_edit:first").css("display", "none");
	
	receiver.css("white-space", "normal");
	commentText = receiver.text();
	
	editDiv = $('#edit_comment_template').clone();
	editDiv.attr("id", "edit_comment-" + event.data.op.id);
	editDiv.css("display", "block");
	
	textarea = $("#edit_comment", editDiv);
	textarea.val(commentText);
	textarea.keyup(expandTextAreaOnKeyUp);
	
	switch (event.data.op.eval){
	case "+":
		$("#radio1", editDiv).attr("checked", true);
		break;
	case "-":
		$("#radio2", editDiv).attr("checked", true);
		break;
	case "=":
		$("#radio2", editDiv).attr("checked", true);
		break;
	}
	
	$("input[type='submit']", editDiv).click({"op": event.data.op}, updateOpinion);
	
	//editDiv
	receiver.html(editDiv);
	
	expandTextAreaOnKeyUp.call(textarea[0]);
}

function showDeleteDialog(event){
	g_deleteOp = event.data.op;
	g_deleteDialog.dialog("open");
}

function incrementNumber(selector, delta){
	var intVal = parseInt(selector.attr("int_value")); //parseInt(selector.text());
	var newValue = intVal + delta;
	
	selector.attr("int_value", newValue);
	
	if (delta > 0) {
		newValue -= 1;
		newValue = setMeInValue(newValue);
	}
	
	selector.html(newValue);
}

function incrementAndAnimate(container, textSelector, delta) {
	container.css("background-color", delta > 0 ? "#00FF00": "#FF0000");
	
	incrementNumber($(textSelector, container), delta);
	
	container.animate({
		backgroundColor: "#ffffff"
	}, 4500);
}

function processCreateUpdateResponse(data, displayFunction) {
	if (data.path_to_base) {
		g_pathToVote = data.path_to_base.reverse();
	}

	if (data.opinion.has_content){
		data.opinion.creator = {"id": g_currentUserName};
		displayComment(data.opinion, null, displayFunction);
	}
	
	if (data.impact.modified_opinion) {
		if (data.impact.modified_opinion.modification == 'neutralization') {
			setCommentEval($('#comment-' + data.impact.modified_opinion.obj.id + ' #comment_eval:first'), "=");
		}
	}
	
	for (i in data.impact.attention_deltas) {
		delta = data.impact.attention_deltas[i];
		
		positive_attention_text = $("#evaluations-" + delta.opinion_id + " #positive_attention_text:first");
		if (delta.positive_attention_delta != 0) {
			incrementAndAnimate(positive_attention_text, "#positive_attention", delta.positive_attention_delta);
		}
		
		negative_attention_text = $("#evaluations-" + delta.opinion_id + " #negative_attention_text:first");
		if (delta.negative_attention_delta != 0) {
			incrementAndAnimate(negative_attention_text, "#negative_attention", delta.negative_attention_delta);
		}
	}
}

function postSubComment(event){
	commentText = $(event.data.commentFormSelector +" > textarea").val();
	//alert(commentText + " " + event.data.parent);
	aoData = [];
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	aoData.push({
		"name" : "parent",
		"value" : event.data.parent
	});
	aoData.push({
		"name" : "evaluation",
		"value" : event.data.evaluation
	});
	aoData.push({
		"name" : "title",
		"value" : commentText
	});
	
	$.ajax({
		"dataType" : 'json',
		"type" : "POST",
		"url" : "/opinion/create_opinion",
		"data" : aoData,
		"success" : function(data) {
			processCreateUpdateResponse(data, event.data.displayFunction);
			$('#comment_form textarea').val("");
		},
		"error" : onOpinionFailure
	});
}


function updateOpinion(event) {
	aoData = [];
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	aoData.push({
		"name" : "opinion_id",
		"value" : event.data.op.id
	});
	
	aoData.push({
		"name" : "title",
		"value" : $('#edit_comment-' + event.data.op.id + " > textarea").val()
	});
	
	aoData.push({
		"name" : "evaluation",
		"value" : $('#edit_comment-' + event.data.op.id + " input[name=radio]:checked").val()
	});
	
	$.ajax({
		"dataType" : 'json',
		"type" : "POST",
		"url" : "/opinion/update",
		"data" : aoData,
		"success" : function(data) {
			if (!data.opinion.has_content) {
				//the opinion text was delete => remove the comment div
				$("#comment-" + data.opinion.id).remove();
			}
			processCreateUpdateResponse(data, null);
		},
		"error" : onOpinionFailure
	});
}

function deleteOpinion(opinionId) {
	aoData = [];
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	aoData.push({
		"name" : "opinion_id",
		"value" : opinionId
	});
	
	$.ajax({
		"dataType" : 'json',
		"type" : "POST",
		"url" : "/opinion/delete",
		"data" : aoData,
		"success" : function(data) {
			$("#comment-" + opinionId).remove();
		},
		"error" : onOpinionFailure
	});
}

function sendGetPathToMyVote(onComplete){
	aoData = [];
	
	aoData.push({
		"name" : "base_id",
		"value" : g_opinionId
	});
	aoData.push({
		"name" : "access_token",
		"value" : g_currentToken
	});
	aoData.push({
		"name" : "non_neutral_only",
		"value" : 1
	});
	aoData.push({
		"name" : "order",
		"value" : "newest"
	});
	aoData.push({
		"name" : "include_path",
		"value" : 1
	});
	
	$.ajax({
		"dataType" : 'json',
		"type" : "GET",
		"url" : "/opinion/get_user_opinions",
		"data" : aoData,
		"success" : function(data) {
				g_pathToVote = new Array();
				if (data.page.length > 0) {
					if (data.page[0].path.length > 0){
						g_pathToVote = data.page[0].path;
						
						//add the actual opinion
						g_pathToVote.push(data.page[0]);
						

					}
				}
				onComplete();
			},
		"error" : onOpinionFailure
		});
}

function displayPathToMyVote() {
	var parentOp = null;
	for (indx in g_pathToVote) {
		if (g_pathToVote[indx].id != g_opinionId && g_pathToVote[indx].title) {
			displayComment(g_pathToVote[indx], null, function(commentDiv){
				if (parentOp.id == g_opinionId) {
					$('#article_comments').append(commentDiv);
				} else {
					$('#sub_comments-' + parentOp.id).append(commentDiv);
				}
				
			});
		}
		parentOp = g_pathToVote[indx];
	}
}